<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人员编辑</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f7f7f7;
            color: #333;
        }

        .admin-layout {
            background-color: #f7f7f7;
        }

        .content-wrapper {
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 24px;
            margin: 20px;
        }

        .content-header {
            margin-bottom: 24px;
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 16px;
        }

        #pageTitle {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        /* iOS风格表单 */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-label {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 8px;
            display: block;
        }

        .required-field::after {
            content: "*";
            color: #dc3545;
            margin-left: 4px;
        }

        .form-control, .form-select {
            height: 44px;
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 0 16px;
            font-size: 16px;
            transition: all 0.2s ease;
            width: 100%;
            background-color: #f9f9f9;
        }

        .form-control:focus, .form-select:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.1);
            background-color: #fff;
            outline: none;
        }

        /* 按钮样式 */
        .btn {
            height: 44px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-primary:hover {
            background-color: #218838;
            border-color: #1e7e34;
        }

        .btn-secondary {
            background-color: #f2f2f7;
            border-color: #f2f2f7;
            color: #28a745;
        }

        .btn-secondary:hover {
            background-color: #e5e5ea;
            border-color: #e5e5ea;
        }

        .btn-action {
            min-width: 120px;
        }

        /* 左侧菜单样式 */
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .content-wrapper {
                padding: 16px;
                margin: 10px;
            }

            .form-container {
                padding: 0;
            }
        }
    </style>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html" class="active">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="*">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/editproduct_plan.html">编辑生产计划</a></li>
                    <li><a href="../product/viewproduct_plan.html">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>

    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="content-header">
                <h2 id="pageTitle">添加人员</h2>
            </div>

            <div class="content-body">
                <div class="form-container">
                    <form id="personForm">
                        <input type="hidden" id="personId">

                        <!-- 移除工号输入框 -->

                        <div class="form-group">
                            <label for="name" class="form-label required-field">姓名</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>

                        <div class="form-group">
                            <label for="department" class="form-label required-field">部门</label>
                            <select class="form-select" id="department" required>
                                <option value="">-- 选择部门 --</option>
                                <option value="表面处理车间">表面处理车间</option>
                                <option value="锻压车间">锻压车间</option>
                                <option value="组装车间">组装车间</option>
                                <option value="质检车间">质检车间</option>
                                <option value="机加车间">机加车间</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="entryDate" class="form-label required-field">入职时间</label>
                            <input type="date" class="form-control" id="entryDate" required>
                        </div>

                        <div class="form-group">
                            <label for="education" class="form-label">最高学历</label>
                            <select class="form-select" id="education">
                                <option value="">-- 选择学历 --</option>
                                <option value="高中">高中</option>
                                <option value="专科">专科</option>
                                <option value="本科">本科</option>
                                <option value="硕士">硕士</option>
                                <option value="博士">博士</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="major" class="form-label">专业</label>
                            <input type="text" class="form-control" id="major">
                        </div>

                        <div class="form-group">
                            <label for="title" class="form-label">职称</label>
                            <input type="text" class="form-control" id="title">
                        </div>

                        <div class="form-group">
                            <label for="phone" class="form-label required-field">手机号</label>
                            <input type="tel" class="form-control" id="phone" required>
                        </div>

                        <div class="form-group">
                            <label for="address" class="form-label">家庭住址</label>
                            <input type="text" class="form-control" id="address">
                        </div>

                        <div class="form-group">
                            <label for="profile" class="form-label">个人简介</label>
                            <textarea class="form-control" id="profile" rows="4"></textarea>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <button type="button" class="btn btn-secondary btn-action" onclick="goBack()">返回</button>
                            <button type="submit" class="btn btn-primary btn-action">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>
</div>

<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let isEditMode = false;
    let personId = null;

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function () {
        // 菜单展开/收起功能
        var menuItems = document.querySelectorAll('.menu-item > a');
        menuItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                var parent = item.parentElement;
                // 只允许单开一个折叠区
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            });
        });

        // 添加首页链接的点击事件
        document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
            e.preventDefault(); // 阻止默认行为
            window.location.href = '../homepage/manager_home.html'; // 跳转到管理员首页
        });

        // 默认展开人员管理菜单
        const personMenuItem = document.querySelector('.menu-item:nth-child(2)');
        if (personMenuItem) {
            personMenuItem.classList.add('active');
        }

        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });

        // 检查URL参数，判断是编辑还是新增
        const urlParams = new URLSearchParams(window.location.search);
        personId = urlParams.get('id');

        if (personId) {
            // 编辑模式
            isEditMode = true;
            document.getElementById('pageTitle').textContent = '编辑人员';
            document.getElementById('personId').value = personId;
            loadPersonData(personId);
        } else {
            // 新增模式
            document.getElementById('pageTitle').textContent = '添加人员';
        }

        // 表单提交事件
        document.getElementById('personForm').addEventListener('submit', function (e) {
            e.preventDefault();
            savePerson();
        });
    });

    // 加载人员数据
    async function loadPersonData(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/persons/${id}`);
            if (!response.ok) {
                throw new Error('获取人员数据失败');
            }

            const person = await response.json();

            // 填充表单
            // 不再需要设置工号字段
            document.getElementById('name').value = person.name || '';
            document.getElementById('department').value = person.department || '';
            document.getElementById('entryDate').value = person.entryDate || '';
            document.getElementById('education').value = person.education || '';
            document.getElementById('major').value = person.major || '';
            document.getElementById('title').value = person.title || '';
            document.getElementById('phone').value = person.phone || '';
            document.getElementById('address').value = person.address || '';
            document.getElementById('profile').value = person.profile || '';

        } catch (error) {
            console.error('加载人员数据失败:', error);
            alert('加载人员数据失败，请稍后重试');
        }
    }

    // 保存人员
    async function savePerson() {
        // 表单验证
        const form = document.getElementById('personForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        // 获取表单数据
        const personData = {
            // 在编辑模式下，需要保留原有工号
            name: document.getElementById('name').value,
            department: document.getElementById('department').value,
            entryDate: document.getElementById('entryDate').value,
            education: document.getElementById('education').value,
            major: document.getElementById('major').value,
            title: document.getElementById('title').value,
            phone: document.getElementById('phone').value,
            address: document.getElementById('address').value,
            profile: document.getElementById('profile').value
        };

        try {
            let url = 'http://localhost:8080/api/persons';
            let method = 'POST';

            if (isEditMode && personId) {
                // 编辑模式
                url = `${url}/${personId}`;
                method = 'PUT';
                personData.id = parseInt(personId);

                // 获取原有人员信息以保留工号
                const response = await fetch(`http://localhost:8080/api/persons/${personId}`);
                if (response.ok) {
                    const existingPerson = await response.json();
                    personData.jobNumber = existingPerson.jobNumber;
                }
            }

            console.log('发送的数据:', personData);

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(personData)
            });

            if (!response.ok) {
                const errorText = await response.text();
                console.error('服务器错误:', errorText);
                throw new Error('保存人员数据失败: ' + errorText);
            }

            const result = await response.json();
            alert(result.message || '保存成功');

            // 返回列表页
            window.location.href = 'person_list.html';

        } catch (error) {
            console.error('保存人员数据失败:', error);
            alert('保存人员数据失败，请稍后重试: ' + error.message);
        }
    }

    // 返回列表页
    function goBack() {
        window.location.href = 'person_list.html';
    }

    // 退出登录
    function logout() {
        // 添加确认提示
        if (confirm('确定要退出登录吗？')) {
            // 清除本地存储的登录信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');

            // 跳转到登录页面
            window.location.href = 'login.html';
        }
    }
</script>
</body>
</html>